package com.newegg.research;

import java.util.List;

public class StringUtil
{
	public static int getRepeatTimes(final String s, final String n,
			final boolean isCaseSentense)
	{
		int x = n.length();
		int count = 0;
		for (int i = 0; i < s.length() - x; i++)
		{
			String sub = s.substring(i, i + x);
			if (isCaseSentense)
			{
				if (sub.equals(n))
					count++;
			} else
			{
				if (sub.equalsIgnoreCase(n))
					count++;
			}
		}
		return count;
	}

	/** 计算最大子序列，支持拉丁语系及中文。其中拉丁语系以空格为单词分隔，中文使用二分法进行分词 */
	public static Object[] getMaxSubString(final String a, final String b,
			final boolean isCaseSentive)
	{
		StringTokenizer tokenizer = new StringTokenizer();
		List<String> x;
		List<String> y;

		if (!isCaseSentive)
		{
			x = tokenizer.participle(a.toLowerCase());
			y = tokenizer.participle(b.toLowerCase());
		} else
		{
			x = tokenizer.participle(a);
			y = tokenizer.participle(b);
		}

		if (a.length() < 2 || b.length() < 2)
		{
			return new Object[]
			{ 0, 0, null };
		}

		if (x.size() < y.size())
		{
			List<String> tmp = x;
			x = y;
			y = tmp;
		}
		StringBuffer sb = new StringBuffer();
		int startIndex = 0;
		int matchCount = 0;
		for (int i = 0; i < y.size(); i++)
		{
			for (int j = startIndex; j < x.size(); j++)
			{
				if (x.get(j).equals(y.get(i)))
				{
					matchCount++;
					sb.append(x.get(j) + " ");
					startIndex = j + 1;
					break;
				}
			}
		}

		return new Object[]
		{ 100 * matchCount / x.size(), 100 * matchCount / y.size(),
				sb.toString() };
	}

}
